/**
 * Created by spatra on 15-1-6.
 */

define(['lessonDiscussionJS/module'], function(lessonDiscussionModule){

  /**
   * 讨论列表控制器
   */
  lessonDiscussionModule.controller('DiscussionListController', ['$scope', '$rootScope', '$stateParams', 'discussionList', 'DiscussionService', 'LoginStatusService',
    function($scope, $rootScope, $stateParams, discussionList, DiscussionService, LoginStatusService){

      var sourceList = discussionList;
      $scope.filterCondObj = {};
      $scope.currentLessonId = $stateParams['lessonId'];
      $scope.withoutFiltering = true;
      $scope.currentUserId = LoginStatusService.get('personalInfo.id');

      //测试用
      $scope.discussionFilterConditions = {
        'user': [
          {label: '所有人', cond:'optionGetAll'},
          //{label: '请求我关注的', cond:'optionGetFollow'},
          {label: '我所创建的', cond: 'optionGetCreate'}
        ]
        //'open': [
        //  {label: '全部的', cond:'statusGetAll'},
        //  {label: '开启的', cond: 'statusGetOpen'},
        //  {label: '关闭的', cond: 'statusGetClose'}
        //]
      };

      function filterDiscussion(source, condObj){
        if( condObj['user'] == 'optionGetAll' || condObj['user'] === undefined){
          $scope.withoutFiltering = true;
          return source;
        }

        var rtn = [];
        source.forEach(function(currentDiscussion){
          if( currentDiscussion.creater_id == $scope.currentUserId ){
            rtn.push(currentDiscussion);
          }
        });

        $scope.withoutFiltering = false;
        return rtn;
      }

      $scope.$watch('filterCondObj', function(newValue){
        $scope.discussionList = filterDiscussion(sourceList, newValue);
      }, true);

      function reloadDiscussion(){
        DiscussionService.accessor['setParentResourceId']($stateParams);

        DiscussionService.accessor.get()
          .success(function(data){
            sourceList = data;
            $scope.discussionList = filterDiscussion(sourceList, $scope.filterCondObj);
          })
          .error(function(data){
            console.error(data);
          });
      }
      reloadDiscussion();

      //当收到事件广播时重新加载讨论列表
      $rootScope.$on('discussionList:reload', function(){
        reloadDiscussion();
      });

  }]);//End of --> DiscussionListController

  /**
   * 用于新建讨论的控制器
   */
  lessonDiscussionModule.controller('DiscussionCreatingController', ['$scope', '$state', 'currentLessonId', 'DiscussionService',
    function($scope, $state, currentLessonId, DiscussionService){

      function resetDiscussion(){
        $scope.addDiscussion = {};
      }

      $scope.currentLessonId = currentLessonId;
      resetDiscussion();

      $scope.reset = resetDiscussion;

      /**
       * 新建讨论
       */
      $scope.add = function(){
        DiscussionService.accessor.store($scope.addDiscussion)
          .success(function(){
            $scope.$emit('message:success', {
              title: '操作成功',
              msg: '讨论已添加'
            });

            $scope.$emit('discussionList:reload');

            //如果成功添加，还自动跳转回列表
            $state.go('lesson.show.discussion', {
              lessonId: currentLessonId
            });
          })
          .error(function(data){
            console.error(data);
            $scope.$emit('message:error', {
              title: '操作失败',
              msg: data.error
            })
          })
      };

  }]);//End of --> DiscussionCreatingController

  /**
   * 此控制器对应查询具体的讨论信息
   */
  lessonDiscussionModule.controller('DiscussionInfoController', ['$scope', '$modal', '$state', '$stateParams', 'currentLessonId', 'currentDiscussion', 'lessonDiscussionModuleBaseUrl', 'DiscussionService',
    function($scope, $modal, $state, $stateParams, currentLessonId, currentDiscussion, lessonDiscussionModuleBaseUrl, DiscussionService){
      /*
        初始化用到的变量
       */
      $scope.currentLessonId = currentLessonId;
      $scope.currentDiscussion = currentDiscussion;

      /*
        重新加载讨论
       */
      DiscussionService.accessor['setParentResourceId']($stateParams);
      function reloadDiscussion(){
        DiscussionService.accessor.show($stateParams['discussionId'])
          .success(function(data){
            $scope.currentDiscussion = data;
          })
          .error(function(data){
            console.error(data);
            $scope.$emit('message:error', {
              msg: '重新加载讨论失败'
            })
          });
      }

      $scope.goBack = function(){
        $scope.$emit('discussionList:reload');
        $state.go('lesson.show.discussion', $stateParams);
      };

      /*
        添加新的回复
       */
      $scope.addReply = function () {
        /*
          生成模态框
         */
        $scope.addReplyModal = $modal.open({
          templateUrl: lessonDiscussionModuleBaseUrl + 'tpls/add-discussion-reply-modal.html',
          controller: 'AddDiscussionReplyController',
          size: 'lg'
        });

        $scope.addReplyModal.result
          .then(function(data){
            DiscussionService.addReply(data, $stateParams)
              .success(function(){
                reloadDiscussion();
                $scope.$emit('message:success', {
                  title: '操作成功',
                  msg: '回复已成功添加'
                });
              })
              .error(function(data){
                console.error(data);
                $scope.$emit('message:error', {
                  title: '操作失败',
                  msg: data.error
                });
              });
          });
      };//End of --> function:addReply

  }]);//End of --> DiscussionInfoController


  /**
   * 此控制器用于新建讨论的回复
   */
  lessonDiscussionModule.controller('AddDiscussionReplyController', ['$scope', '$modalInstance',
    function($scope, $modalInstance){

      $scope.content;

      $scope.cancel = function(){
        $modalInstance.dismiss('cancel');
      };

      $scope.ok = function(){
        $modalInstance.close({
          content: $scope.content
        });
      }
  }]);//End of --> AddDiscussionReplyController
});